﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.EntityFrameworkCore;
using Panuon.UI.Silver;
using StockTrading.Model;
using StockTrading.ViewModel;

namespace StockTrading.View
{
    /// <summary>
    /// Main.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : WindowX
    {
        private readonly SignInView signIn;
        private readonly ApplicationDbContext _context;

        public MainViewModel MainViewModel { get; set; }

        public MainView(SignInView signIn, MainViewModel  mainViewModel,ApplicationDbContext context)
        {
            _context = context;
            InitializeComponent();
            this.signIn = signIn;
            MainViewModel = mainViewModel;
            this.DataContext = mainViewModel;
        }
        private void win_Loaded(object sender, EventArgs e)
        {
            signIn.ShowDialog();
            
            DataContext = MainViewModel;
        }

        private void win_Initialized(object sender, EventArgs e)
        {
            try
            {
                //try yo migrate database
                _context.Database.Migrate();
            }
            catch (Exception)
            {


            }
            // this is for demo purposes only, to make it easier
            _context.Database.EnsureCreated();
            // load the entities into EF Core
            _context.Users.Load();
            //查询root
            var user = _context.Users.Where(x => x.LoginName == "root").FirstOrDefault();
            if (user == null)
            {
                //如果root不存在，添加root账号
                _context.Users.Add(new User()
                {
                    Name = "root",
                    LoginName = "root",
                    Password = "admin123...",
                    IsAdmin = true,
                    CnyFree = 9999999999999,
                    CnyFreezed = 0
                });
                _context.SaveChanges();
            }
        }
    }
}
